package org.gesplan.util;

import java.awt.Cursor;
import java.awt.Toolkit;
import java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.SortOrder;
import javax.swing.SwingWorker;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Roger
 */
public class SortWorker extends SwingWorker<Void, Void> {

    private int column;
    private int old_column;
    private boolean order;
    private JProgressBar dbTaskProgressBar;
    private final JTable masterTable;
    private JPanel panel = null;

    
    public SortWorker(JPanel panel, JTable masterTable) {
        this.panel = panel;
        this.masterTable = masterTable;
    }
    
    
    public void setColumn(int column, boolean order) {
        old_column = this.column;
        this.column = column;
        this.order = order;
    }
    
    
    /*
     * Main task. Executed in background thread.
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public Void doInBackground() {
        
        if (dbTaskProgressBar == null) {
            dbTaskProgressBar = Utils.getProgressBar();
        }        
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));        
        //Initialize progress property.
        dbTaskProgressBar.setValue(0);
        dbTaskProgressBar.setIndeterminate(true);
        TableRowSorter trs = new TableRowSorter();
        trs.setModel(masterTable.getModel());
        masterTable.setRowSorter(trs);
        ArrayList<RowSorter.SortKey> sortKeys = new ArrayList<>();
        trs.setSortable(column, true);
        SortOrder s;
        //System.out.println("OLD: " + old_column + " NEW: " + column);
        if (old_column == column) {
            if (order) {
                order = false;
                s = SortOrder.ASCENDING;
                //System.out.println("1. Order: " + order + " Sort: " + s.toString());
            } else {
                order = true;
                s = SortOrder.DESCENDING;
                //System.out.println("2. Order: " + order + " Sort: " + s.toString());
            }
        } else {
            order = false;
            s = SortOrder.ASCENDING;
            //System.out.println("3. Order: " + order + " Sort: " + s.toString());
        }
        sortKeys.add(new RowSorter.SortKey(column, s));
        trs.setSortKeys(sortKeys);
        trs.sort();
        //System.out.println("He ordenat ja");
        return null;
        
    }

    
    /*
     * Executed in event dispatch thread
     */
    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        dbTaskProgressBar.setIndeterminate(false);
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }

}